<template>
  <div class="mydrawer">
    <el-drawer v-model="drawer.visible" title="资产详情" size="50%" close-on-click-modal @close="hide">
      <div class="text-sm font-semibold">小程序信息</div>
      <div class="grid gap-4 grid-cols-3 mt-4">
        <div style="min-width: 30%">
          <div class="text-xs">小程序名称</div>
          <div class="text-xs text-gray mt-1">{{ shareInfo.appName }}</div>
        </div>
        <div style="min-width: 30%">
          <div class="text-xs">小程序备注</div>
          <div class="text-xs text-gray mt-1">{{ shareInfo.remark }}</div>
        </div>
        <div style="min-width: 30%">
          <div class="text-xs">APPID</div>
          <div class="text-xs text-gray mt-1">{{ shareInfo.appId }}</div>
        </div>
        <div style="min-width: 30%">
          <div class="text-xs">细分分类</div>
          <div class="text-xs text-gray mt-1">{{ shareInfo.tagInfoDesc }}</div>
        </div>
      </div>
      <div class="text-sm font-semibold mt-1">链接</div>
      <div class="mt-4 mb-5 flex justify-between">
        <el-button type="primary" @click="addLink">添加链接</el-button>
      </div>

      <el-table :data="linkList" style="width: 100%">
        <el-table-column prop="link" label="链接">
          <template #default="scope">
            <div class="overflow-hidden text-ellipsis whitespace-nowrap max-w-full">{{ scope.row.link }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="linkRemark" label="备注" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-link type="primary" disabled v-if="false" @click="previewLink(scope.row.link)">预览</el-link>
            <el-link type="primary" @click="editLink(scope.row)">编辑</el-link>
            <el-link class="ml-[5px]" type="primary" @click="copyLink(scope.row.link)">复制</el-link>
            <el-link class="ml-[5px]" type="primary" v-hasPermi="['advertisement:account:remove']" @click="delLink(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getLinkList"
      />
    </el-drawer>
    <LinkAdd ref="linkAddRef" @updateList="getLinkList" />
    <LinkEdit ref="linkEditRef" @updateLink="updateLink" />
  </div>
</template>
<script setup lang="ts">
import { queryToolsAssetLinkList, updateToolsMicroApp } from '@/api/advertisement/byte';
import { ByteVO, queryToolsAssetLinkListVO, TypeUpdateMicroVO } from '@/api/advertisement/byte/types';
import LinkAdd from './linkAdd.vue';
import LinkEdit from './linkEdit.vue';
const shareInfo = ref<ByteVO>();
const linkList = ref();
const linkAddRef = ref();
const linkEditRef = ref();
const drawer = reactive<DialogOption>({
  visible: false
});
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
});

enum OperateType {
  NEW = 'NEW',
  MODIFY = 'MODIFY',
  DELETE = 'DELETE'
}

//获取链接列表
const getLinkList = async () => {
  console.log('🚀 ~ getLinkList ~ shareInfo:', shareInfo.value);
  const data: queryToolsAssetLinkListVO = {
    accountId: shareInfo.value.accountId,
    advertiserId: shareInfo.value.advertiserId,
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    instanceId: shareInfo.value.instanceId
  };
  try {
    const res = await queryToolsAssetLinkList(data);
    linkList.value = res.data.list;
    total.value = res.data.pageInfo.totalNumber;
  } catch (error) {
    console.log(error);
  }
};

// 预览链接
const previewLink = async (link: string) => {};

// 编辑链接
const editLink = (row: any) => {
  linkEditRef.value.openDialog(row);
};

// 删除链接
const delLink = async (row: any) => {
  try {
    // 使用 ElMessageBox 显示确认对话框
    await ElMessageBox.confirm('是否确认删除链接?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    // 调用删除接口
    await updateLink(row, OperateType.DELETE);
    ElMessage.success('删除成功');
  } catch (error) {
    // 用户点击取消时会进入这里
    if (error === 'cancel') {
      ElMessage.info('删除操作已取消');
    } else {
      ElMessage.error('删除失败');
    }
  }
};

const updateLink = async (row: any, type: OperateType) => {
  console.log('🚀 ~ updateLink ~ row:', row);
  const { accountId, advertiserId, instanceId, appId, tagInfo } = shareInfo.value;
  const { startPage, startParam, link, linkId } = row;
  const remark = row.linkRemark;
  try {
    // 调用删除接口
    await updateToolsMicroApp({
      accountId,
      advertiserId,
      instanceId,
      appId,
      tagInfo,
      appPage: [{ id: linkId, link, startPage, startParam, remark, operateType: type }]
    });
    getLinkList(); // 刷新列表
  } catch (error) {
    console.error('删除链接失败:', error);
    throw error;
  }
};

// 复制链接
const copyLink = (link: string) => {
  navigator.clipboard
    .writeText(link)
    .then(() => {
      ElMessage.success('复制成功');
    })
    .catch(() => {
      ElMessage.error('复制失败');
    });
};

// 添加链接
const addLink = () => {
  linkAddRef.value.openDialog(shareInfo.value);
};

/**
 *  显示
 */
const show = (info: ByteVO) => {
  if (info) {
    console.log('🚀 ~ show ~ info:', info);
    shareInfo.value = info;
    getLinkList();
  }
  drawer.visible = true;
  nextTick(() => {});
};

/**
 * 隐藏
 */
const hide = () => {
  drawer.visible = false;
};

defineExpose({
  show,
  hide
});
</script>
